package band.wukong.practice.webservice.kh.sample11;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.xml.namespace.QName;
import javax.xml.soap.*;
import javax.xml.ws.handler.MessageContext;
import javax.xml.ws.handler.soap.SOAPHandler;
import javax.xml.ws.handler.soap.SOAPMessageContext;
import java.util.Iterator;
import java.util.Set;

/**
 * @author wukong(wukonggg@139.com)
 */
public class LicenseHandler implements SOAPHandler<SOAPMessageContext> {

    private static final Logger logger = LoggerFactory.getLogger(LicenseHandler.class);

    @Override
    public Set<QName> getHeaders() {
        return null;
    }

    @Override
    public boolean handleMessage(SOAPMessageContext context) {
        try {
            Boolean out = (Boolean) context.get(SOAPMessageContext.MESSAGE_OUTBOUND_PROPERTY);
            if (!out) {
                SOAPEnvelope envelope = context.getMessage().getSOAPPart().getEnvelope();
                SOAPHeader header = envelope.getHeader();
                if (null == header) {
                    return true;
                } else {
                    @SuppressWarnings("unchecked")
                    Iterator<SOAPHeaderElement> iterator = header.getChildElements();
                    while (iterator.hasNext()) {
                        SOAPElement ele = iterator.next();
                        if (ele.getLocalName().equals("licenseInfo")) {
                            logger.info("Server LicenseInfo: " + ele.getTextContent());
                        }
                    }
                }
            }
            return true;
        } catch (SOAPException e) {
            e.printStackTrace();
            logger.error(e.getMessage());
        }
        return false;
    }

    @Override
    public boolean handleFault(SOAPMessageContext context) {
        return false;
    }

    @Override
    public void close(MessageContext context) {

    }
}
